package com.eystar.pdc.model;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.eystar.ext.kit.page.PageOrder;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;
import com.eystar.pdc.util.LoginUtil;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

import cn.hutool.core.util.StrUtil;

/**
 * 关键字Model
 * @author Your_Name
 *
 */
@TableBind(tableName = "t_pdc_auth_sign")
public class AuthSign extends ModelExt<AuthSign> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static AuthSign dao = new AuthSign();
	
	/**
	 * 分页查找对象
	 *
	 * @param order
	 * @param user
	 * @return
	 */
	public Page<AuthSign> paginate(PageOrder order, AuthSign authSigns) {
		SqlPara sqlPara = getSqlPara("pdc.auth_sign.paginate",authSigns);
		return paginate(order.getPageNum(), order.getPageSize(), sqlPara);
	}
	
	/**
	 * 查询所有的关键字
	 * @return
	 */
	public List<AuthSign> findAll() {
		SqlPara sqlPara = getSqlPara("pdc.auth_sign.paginate");
		return find(sqlPara);
	}
	
	/**
	 * 根据某个角色查询该角色拥有的所有权限关键字
	 * @param role
	 * @return
	 */
	public Set<String> findAuthSignSetByRole(Role role){
		List<Record> records = new ArrayList<Record>();
		// 如果是超级管理员的话，拥有所有的资源关键字
		if (role.getInt("role_flag") == LoginUtil.ROLE_SUPER) {
			records = Db.find(getSql("pdc.resource.findAll"));
		}else {
			String roleIds = Role.dao.findRoleIdsRecursion(role.getStr("id"));
			Kv kv = Kv.by("ids", StrUtil.split(roleIds, ","));
			SqlPara sqlPara = getSqlPara("pdc.resource.findAuthSignSetByRole", kv);
			records = Db.find(sqlPara);
		}
		Set<String> authorities = new HashSet<String>();
		for (Record record : records) {
			String remark = record.getStr("res_remark");
			if (StrUtil.isNotBlank(remark)) {
				String authSigns = record.getStr("auth_signs");
				for (String authSign : StrUtil.split(authSigns, ",")) {
					authorities.add(remark+"_"+authSign);
				}
			}
		}
		return authorities;
	}
}